<?php
/**
 * Created by PhpStorm.
 * User: gqc
 * Date: 2017/1/1
 * Time: 19:55
 */
namespace Api\Service\Amazon;
use Home\Service\CommonService;

class InboundService extends CommonService{
    /*inbound模型*/
    protected $inboundModel = NULL;

    protected $accountsModel = NULL;

    public function __construct() {
        $this->inboundModel = D('Api/Amazon/Inbound','Model');
        $this->accountsModel = D('Api/Amazon/Accounts','Model');
        $this->addressModel =  D('Api/Amazon/AccountSite','Model');
    }
    /*
     * 描述 : 返回创建入库货件所需信息
     * 参数 :
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          LabelPrepPreference :  	您对入库货件标签准备的选项设置,可以不填,默认值为SELLER_LABEL,
     *          shipmentPlanItems   : 入库货件中各商品的 SKU 和数量信息 数组 {
     *              数组 {
     *                  SellerSku             : 商品的卖家SKU,必填,
     *                  Quantity              : 商品数量,必填,
     *              },...
     *          }
     *      }
     * 返回 : 用于创建入库货件的入库货件信息
     *      数组 {
     *          ShipmentId : 货件编号,
     *          ShipToAddressId :
     *          ShipFromAddressId :
     *          DestinationFulfillmentCenterId : 您的货件将运至的亚马逊配送中心的编号,
     *          Items : 数组{
     *                      数组 {
     *                      SellerSKU             : 商品的卖家SKU,
     *                      FulfillmentNetworkSKU : 商品的亚马逊配送网络SKU,
     *                      Quantity              : 要配送的商品数量,
     *                  },...
     *           },...
     * 作者：kelvin 2017-01-06
    */
    public function createInboundShipmentPlan ($accountId, $options = array()) {
        $shipmentPlanItems = !empty($options['shipmentPlanItems'][0]['SellerSKU']) && !empty($options['shipmentPlanItems'][0]['Quantity']);

        if(!$shipmentPlanItems) return NULL;
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        $Address = $this->addressModel->getAccountShipFromAddress($accountId);
        $options['ShipFromAddress']['Name'] = $Address['Name'];
        $options['ShipFromAddress']['AddressLine1'] = $Address['AddressLine1'];
        $options['ShipFromAddress']['AddressLine2'] = $Address['AddressLine2'];
        $options['ShipFromAddress']['City'] = $Address['City'];
        $options['ShipFromAddress']['StateOrProvinceCode'] = $Address['Province'];
        $options['ShipFromAddress']['PostalCode'] = $Address['PostalCode'];
        $options['ShipFromAddress']['CountryCode'] = $Address['CountryCode'];
        $ShipmentsResult = $this->inboundModel->createInboundShipmentPlan($account, $options);
        if($ShipmentsResult['status']==500){
            return array(
                'status' =>'500',
                'msg' => $ShipmentsResult['msg']
            );
            die;
        }
        $arr = array();
        foreach($ShipmentsResult['msg'] as $k =>$v){
            $shipmentName = 'FBA('.date('Y-m-d H:i:s',time()).') '.$k.'-'.$accountId;
            foreach($v['Items'] as $c => $i){
                $arr[$c]['SellerSKU'] = $i['SellerSKU'];
                $arr[$c]['QuantityShipped'] = $i['Quantity'];

            }
            $shipments = array(
                'ShipmentId' => $v['ShipmentId'],
                'InboundShipmentHeader' => array(
                    'ShipmentName' => $shipmentName,
                    'DestinationFulfillmentCenterId' => $v['DestinationFulfillmentCenterId'],
                    'LabelPrepPreference' => 'SELLER_LABEL',
                    'AreCasesRequired' => false,
                    'ShipmentStatus' => 'WORKING',
                ),
                'InboundShipmentItems' => $arr,

            );
            $ShipmentsResult['msg'][$k]['ShipmentName'] = $shipmentName;
            $inboundShipment =$this->createInboundShipment($accountId,$shipments);
        }
        /*调用数据表model将数据插入数据表*/
        if($inboundShipment['status']==500){
            return array(
                'status' =>'500',
                'msg' => $inboundShipment['msg']
            );
            die;
        }else{
            return array(
                'status' => 200,
                'msg' => $ShipmentsResult['msg']
            );
        }
    }
    /* 描述：创建入库货件
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentName : 您为货件选择的名称,请使用命名规则（如货件创建日期）,以帮助您区分不同时间段的货件,必填,
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,必填,
     *              LabelPrepPreference : 入库货件的标签准备首选项,默认SELLER_LABEL,必填,
     *              AreCasesRequired : bool 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *          InboundShipmentItems  : 入库货件中商品的SellerSKU和QuantityShipped信息 数组{
     *              数组{
     *                  SellerSKU : 商品的卖家SKU,
     *                  QuantityShipped : 要配送的商品数量
     *              },...
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-06
     *
     */
    public function createInboundShipment ($accountId, $options = array()) { // By $accountId ?
        $shipmentId = !empty($options['ShipmentId']);
        $inboundShipmentHeader = !empty($options['InboundShipmentHeader'])
            && !empty($options['InboundShipmentHeader']['ShipmentName'])
            && !empty($options['InboundShipmentHeader']['DestinationFulfillmentCenterId'])
            && !empty($options['InboundShipmentHeader']['LabelPrepPreference'])
            && !empty($options['InboundShipmentHeader']['ShipmentStatus']);
        $inboundShipmentItems = !empty($options['InboundShipmentItems'])
            && !empty($options['InboundShipmentItems'][0]['SellerSKU'])
            && !empty($options['InboundShipmentItems'][0]['QuantityShipped']);
        if(!$shipmentId || !$inboundShipmentHeader || !$inboundShipmentItems) return NULL;
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        $Address = $this->addressModel->getAccountShipFromAddress($accountId);
        $options['InboundShipmentHeader']['ShipFromAddress']['Name'] = $Address['Name'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1'] = $Address['AddressLine1'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2'] = $Address['AddressLine2'];
        $options['InboundShipmentHeader']['ShipFromAddress']['City'] = $Address['City'];
        $options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode'] = $Address['Province'];
        $options['InboundShipmentHeader']['ShipFromAddress']['PostalCode'] = $Address['PostalCode'];
        $options['InboundShipmentHeader']['ShipFromAddress']['CountryCode'] = $Address['CountryCode'];
        $ShipmentsResult = $this->inboundModel->createInboundShipment($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：返回入库货件的当前运输信息
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *      }
     * 返回 :
     *      TransportHeader : 数组{
     *          SellerId     : 亚马逊卖家编号,
     *          ShipmentId   : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,
     *          IsPartnered  : 指明 PutTransportContent 请求是否针对亚马逊合作承运人,
     *          ShipmentType : 在 PutTransportContent 请求中指定承运人货件的类型,
     *      },
     *      TransportResult : 数组{
     *          TransportStatus : 亚马逊合作承运人货件的状态
     *      }
     * 作者 : kelvin 2017-01-06
     *
    */
    public function getTransportContent ($accountId, $options = array()) { // By $accountId ?
        $shipmentId = !empty($options['ShipmentId']);

        if(!$shipmentId) return NULL;

        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();

        $ShipmentsResult = $this->inboundModel->getTransportContent($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：返回用于打印入库货件包裹标签的PDF文档数据
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId       : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          PageType         : 表示打印标签时使用的纸张类型
     *          NumberOfPackages : 指示需要贴标的箱子的数量
     *      }
     * 返回 :
     *      数组{
     *          TransportDocument : 用于打印 PDF文档的数据（格式为Base64编码字符串）,
     *          Checksum          : 用于验证PDF文档数据的Base64编码的MD5哈希值
     *      }
     * 作者 : kelvin 2017-01-06
    */
    public function getPackageLabels ($accountId, $options = array()) { // By $accountId ?
        $shipmentId = !empty($options['ShipmentId']);
        $pageType = !empty($options['PageType']);
        $numberOfPackages = !empty($options['NumberOfPackages']);

        if(!$shipmentId || !$pageType || !$numberOfPackages) return NULL;

        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();

        $ShipmentsResult = $this->inboundModel->getPackageLabels($account, $options);


        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }

    /* 描述：更新现有入库货件
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentName : 您为货件选择的名称,请使用命名规则（如货件创建日期）,以帮助您区分不同时间段的货件,必填,
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,必填,
     *              LabelPrepPreference : 入库货件的标签准备首选项,默认SELLER_LABEL,必填,
     *              AreCasesRequired : bool 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *          InboundShipmentItems  : 入库货件中商品的SellerSKU和QuantityShipped信息 数组{
     *              数组{
     *                  SellerSKU : 商品的卖家SKU,
     *                  QuantityShipped : 要配送的商品数量
     *              },...
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-06
     *
    */
    public function updateInboundShipment ($accountId, $options = array()) { // By $accountId ?
        $shipmentId = !empty($options['ShipmentId']);
        $inboundShipmentHeader = !empty($options['InboundShipmentHeader'])
            && !empty($options['InboundShipmentHeader']['ShipmentName'])
            && !empty($options['InboundShipmentHeader']['DestinationFulfillmentCenterId'])
            && !empty($options['InboundShipmentHeader']['LabelPrepPreference'])
            && !empty($options['InboundShipmentHeader']['ShipmentStatus']);
        $inboundShipmentItems = !empty($options['InboundShipmentItems'])
            && !empty($options['InboundShipmentItems'][0]['SellerSKU']);
        if(!$shipmentId || !$inboundShipmentHeader || !$inboundShipmentItems) return 'options false';
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        //发货地址
        $Address = $this->addressModel->getAccountShipFromAddress($accountId);

        $options['InboundShipmentHeader']['ShipFromAddress']['Name'] = $Address['Name'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1'] = $Address['AddressLine1'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2'] = $Address['AddressLine2'];
        $options['InboundShipmentHeader']['ShipFromAddress']['City'] = $Address['City'];
        $options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode'] = $Address['Province'];
        $options['InboundShipmentHeader']['ShipFromAddress']['PostalCode'] = $Address['PostalCode'];
        $options['InboundShipmentHeader']['ShipFromAddress']['CountryCode'] = $Address['CountryCode'];
        $ShipmentsResult = $this->inboundModel->updateInboundShipment($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：取消现有入库货件
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-11
     *
    */
    public function delInboundShipment ($accountId, $shipmentId) { // By $accountId ?
        $options = array(
            'ShipmentId' => $shipmentId,
            'InboundShipmentHeader' => array(
                'ShipmentStatus' => 'DELETED',

            ),
        );
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        //发货地址
        $Address = $this->addressModel->getAccountShipFromAddress($accountId);
        $options['InboundShipmentHeader']['ShipFromAddress']['Name'] = $Address['Name'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1'] = $Address['AddressLine1'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2'] = $Address['AddressLine2'];
        $options['InboundShipmentHeader']['ShipFromAddress']['City'] = $Address['City'];
        $options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode'] = $Address['Province'];
        $options['InboundShipmentHeader']['ShipFromAddress']['PostalCode'] = $Address['PostalCode'];
        $options['InboundShipmentHeader']['ShipFromAddress']['CountryCode'] = $Address['CountryCode'];
        $ShipmentsResult = $this->inboundModel->updateInboundShipment($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：标记发货
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-11
     *
    */
    public function shipInboundShipment ($accountId, $shipmentId) { // By $accountId ?
        $options = array(
            'ShipmentId' => $shipmentId,
            'InboundShipmentHeader' => array(
                'ShipmentStatus' => 'SHIPPED',

            ),
        );
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        //发货地址
        $Address = $this->addressModel->getAccountShipFromAddress($accountId);
        $options['InboundShipmentHeader']['ShipFromAddress']['Name'] = $Address['Name'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1'] = $Address['AddressLine1'];
        $options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2'] = $Address['AddressLine2'];
        $options['InboundShipmentHeader']['ShipFromAddress']['City'] = $Address['City'];
        $options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode'] = $Address['Province'];
        $options['InboundShipmentHeader']['ShipFromAddress']['PostalCode'] = $Address['PostalCode'];
        $options['InboundShipmentHeader']['ShipFromAddress']['CountryCode'] = $Address['CountryCode'];
        $ShipmentsResult = $this->inboundModel->updateInboundShipment($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：取消之前确认的使用亚马逊合作承运人配送入库货件的请求
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId       : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *      }
     * 返回 :
     *      数组{
     *          TransportStatus  : 亚马逊合作承运人货件的状态,
     *      }
     * 作者 : kelvin 2017-01-06
    */
    public function voidTransportRequest ($accountId, $options = array()) { // By $accountId ?
        $shipmentId = !empty($options['ShipmentId']);

        if(!$shipmentId) return NULL;

        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();

        $ShipmentsResult = $this->inboundModel->voidTransportRequest($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /*
     * ShipmentId 用于在特定入库货件中选择商品的货件标识,如果指定了 ShipmentId，则会忽略 LastUpdatedBefore 和 LastUpdatedAfter
     * LastUpdatedAfter 选择在指定时间（或之后）最后更新入库货件商品时所使用的日期，格式为 ISO 8601。包括亚马逊和卖家所进行的更新 如果指定了 LastUpdatedBefore，则必须指定 LastUpdatedAfter
     * LastUpdatedBefore 选择于指定时间（或之前）最后更新入库货件商品时所使用的日期，格式为 ISO 8601。包括亚马逊和卖家所进行的更新 如果指定了 LastUpdatedAfter，则必须指定 LastUpdatedBefore
     * */
    public function listInboundShipmentItems($accountId, $options = array()) {
        $shipmentId = !empty($options['ShipmentId']) ;
        $timeCondition = (
            (empty($options['LastUpdatedAfter']) && empty($options['LastUpdatedBefore'])) ||
            (!empty($options['LastUpdatedAfter']) && !empty($options['LastUpdatedBefore']))
        );
        if(!$shipmentId && !$timeCondition) return NULL;

        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();

        $ShipmentsResult = $this->inboundModel->listInboundShipmentItems($account, $options);
        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }
    /* 描述：返回指定入库货件的商品列表或在指定时间段内更新的商品列表
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     * 返回 :
     *     数组{
     *          Status      : 服务运行状态
     *                          GREEN
     *                             服务运行正常。
     *                          GREEN_I
     *                              服务运行正常。将提供附加信息。
     *                          YELLOW
     *                              服务产生的错误率已超出正常水平，或运行过程中性能有所降低。可能提供附加信息。
     *                          RED
     *                              服务不可用，或错误率已远远超出正常水平。可能提供附加信息
     *          Timestamp   : 指明对运行状态进行评估的时间
     *          }
     * 作者 : kelvin 2017-01-06
    */
    public function getServiceStatus($accountId, $options = array()){
        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();
        $ShipmentsResult = $this->inboundModel->getServiceStatus($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }

    /* 描述：根据您指定的条件返回入库货件列表
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentIdList : 数组{
     *              货件编号,...
     *          }
     *          ShipmentStatusList : 数组{
     *              货件状态,...
     *          }
     *      }
     * 返回 :
     *   数组{
     *      数组{
     *          数组{
     *              ShipmentId      : 货件编号
     *              ShipmentName    : 货件名称
     *              ShipFromAddress : 地址 数组{
     *                  Name                : 名称或公司名称
     *                  AddressLine1        : 街道地址信息
     *                  AddressLine2        : 其他街道地址信息（
     *                  City                : 城市,
     *                  StateOrProvinceCode : 省/自治区/直辖市代码,
     *                  PostalCode          : 邮政编码,
     *                  CountryCode         : 国家地区代码
     *              },
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,
     *              LabelPrepPreference            : 货件的标签选项,
     *              AreCasesRequired               : 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus                 : 入库货件状态
     *          },...
     *      },...
     *  }
     * 作者 : kelvin 2017-01-06
    */
    public function listInboundShipments ($accountId, $options = array()) { // By $accountId ?
        $shipmentidStatusCondition = !empty($options['ShipmentIdList']) || !empty($options['ShipmentStatusList']);
        $timeCondition = (
            (empty($options['LastUpdatedAfter']) && empty($options['LastUpdatedBefore'])) ||
            (!empty($options['LastUpdatedAfter']) && !empty($options['LastUpdatedBefore']))
        );
        if(!$shipmentidStatusCondition || !$timeCondition) return NULL;

        $account = $this->accountsModel->getAccountById($accountId);
        if(empty($account))return array();

        $ShipmentsResult = $this->inboundModel->listInboundShipments($account, $options);

        /*调用数据表model将数据插入数据表*/

        return $ShipmentsResult;//或者插入数据库
    }

    /**
     * 参数:getInboundShipmentsByShipmentId 获取的 ShipmentId
     * 返回:ShipmentId,SellerSKU,FulfillmentNetworkSKU,QuantityShipped
     */
    public function getInboundShipmentItemsByShipmentId ($accountId, $options = array()){
        //调用 getInboundShipmentsByShipmentId 获取 ShipmentId,如果从数据库取的话就不套上一个接口了
        $ShipmentsResult = $this->getInboundShipmentsByShipmentId($accountId, $options);

        $accounts = $this->accountModel->getAccountById($accountId);

        $ItemsData = array();

        if($ShipmentsResult){
            foreach ($ShipmentsResult as $ShipmentId){

                $option['ShipmentId'] = $ShipmentId['ShipmentId'];

                $ItemsResult = $this->inboundModel->lstInboundShipmentItems($accounts, $option);

                if($ItemsResult){
                    do{
                        $ItemsData = array_merge($ItemsData,$ItemsResult['ItemData']['members']);
                        $ItemsResult = $this->inboundModel->listInboundShipmentItemsByNextToken($accounts, array('NextToken' => $ItemsResult['NextToken']));
                    }while(isset($ItemsResult['NextToken']) && $ItemsResult['NextToken'] );
                }else{
                    return false;
                }
            }
        }
        return $ItemsData;
    }


}